package com.hzw.saas.web.im.im.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author sonam
 * @sine 2021/10/21 10:31 上午
 */
@Component("channelInitializer")
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Resource
    private WebSocketImHandler webSocketImHandler;
    @Lazy
    @Resource
    private HttpRequestHandler httpRequestHandler;
    @Resource
    private HeartBeatHandler heartBeatHandler;
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();//接受消息正序，返回倒序
        pipeline.addLast(new HttpServerCodec());    //http解析
        pipeline.addLast(new ChunkedWriteHandler()); //数据分片
        pipeline.addLast(new HttpObjectAggregator(1024 * 64)); //最大帧长度
        pipeline.addLast(httpRequestHandler); //处理业务返回
        pipeline.addLast(new IdleStateHandler(10, 10, 15, TimeUnit.MINUTES));
        pipeline.addLast(heartBeatHandler);
        pipeline.addLast(webSocketImHandler);//自定义业务
    }
}
